#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QPainter>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  ,ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_ListView = new ListView(ui->widget);
    m_Model = new ListModel;
    m_Delegate = new ItemDelegate;

    m_ListView->setItemDelegate(m_Delegate);
    m_ListView->setModel(m_Model);

    connect(m_ListView, &QListView::clicked, this, &MainWindow::viewClicked);
}

MainWindow::~MainWindow()
{

}

ListView::ListView(QWidget *parent) : QListView(parent)
{

}

ListView::~ListView()
{

}

ListModel::ListModel()
{
}

ListModel::~ListModel()
{

}

void ListModel::addRow(Qt::GlobalColor color)
{
    if (m_lstColor.contains(color)) {
        return;
    }

    beginInsertRows(QModelIndex(), m_lstColor.size(), m_lstColor.size());
    m_lstColor.append(color);
    endInsertRows();
}

void ListModel::deleteRow(int index)
{
    beginRemoveRows(QModelIndex(), index, index);
    m_lstColor.removeAt(index);
    endRemoveRows();
}

int ListModel::rowCount(const QModelIndex &parent) const
{
    return m_lstColor.count();
}

int ListModel::columnCount(const QModelIndex &parent) const
{
    return 1;
}

QVariant ListModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::BackgroundColorRole) {
        return static_cast<int>(m_lstColor.at(index.row()));
    }

    return QVariant();
}

QModelIndex ListModel::index(int row, int column, const QModelIndex &parent) const
{
    return createIndex(row, column);
}

QModelIndex ListModel::parent(const QModelIndex &index) const
{
    return QModelIndex();
}

ItemDelegate::ItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
{

}

void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Qt::GlobalColor color = static_cast<Qt::GlobalColor>(index.model()->data(index, Qt::BackgroundColorRole).toInt());

    painter->setBrush(QBrush(color));

    painter->drawRect(option.rect);
}

void MainWindow::on_btnAdd_clicked()
{
    switch (ui->comboBox->currentIndex()) {
    case 0:
        m_Model->addRow(Qt::red);
        break;
    case 1:
        m_Model->addRow(Qt::green);
        break;
    case 2:
        m_Model->addRow(Qt::blue);
        break;
    case 3:
        m_Model->addRow(Qt::cyan);
        break;
    case 4:
        m_Model->addRow(Qt::yellow);
        break;
    case 5:
        m_Model->addRow(Qt::darkBlue);
        break;
    case 6:
        m_Model->addRow(Qt::white);
        break;
    case 7:
        m_Model->addRow(Qt::black);
        break;
    }
}

void MainWindow::on_btnDelete_clicked()
{
    m_Model->deleteRow(m_ListView->currentIndex().row());

    ui->btnDelete->setDisabled(true);
}

void MainWindow::viewClicked(const QModelIndex &index)
{
    ui->btnDelete->setDisabled(false);
}
